<?php
namespace app\admin\controller;
use app\service\appletService;
use app\service\billService;
use app\service\wechatService;
use invoice\Compress;
use invoice\CryptAES;
use invoice\HttpClientService;
use invoice\StaticData;
use printing\printDemo;
use think\Controller;
use think\facade\Db;

class Wechat extends Controller{
	//获取openid
    public function openid()
    {
        $code = request()->get('code');
       
        $appid = "wx29ca4f972fc13f5c";//小程序的唯一标识
        $secret = "a0f906c1d90d333a4235b726adcd80a2";//小程序的AppSecret
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';
        $tmpInfo=(new wechatService())->post_curl($url);
        $tmpInfo = (new wechatService())->object_to_array(json_decode($tmpInfo));
        if (!empty($tmpInfo['errmsg'])) {
            return $tmpInfo['errmsg'];
        } else {
            $user['user_id'] = $tmpInfo['openid'];
            return json_encode($user['user_id']);
        }
    }
	
    //微信创建订单
    public function wxpay()
    {
        $data['sub_openid'] = request()->get('user_id');
        $id = explode(',',request()->get('id'));
        //根据账单编号查询账单金额
        $infolist = (new billService())->billEntryIdInfo($id);
        //echo "<pre>";
        //var_dump($infolist);
        //return json_encode($a);
        
        if(count($infolist) != count($id)-1){
            return json(['info' => '账单信息不完整']);
        }
        $community_name="";
        $community_id="";
        foreach($infolist as $info){
            //查询小区名称
            $community_name = (new billService())->communityMachine($info['community_id'])["community_name"];
            $bill_amount[] = $info['bill_entry_amount'];
            $out_room_id[] = $info['out_room_id'];
            $community_id = $info['community_id'];
            $room_address[] = $info['room_address'];
        }
        $room_address = array_unique($room_address);

        $out_room_id = array_unique($out_room_id);
        
        if(count($out_room_id) !== 1){
            return json(['info' => '账单信息不完整1']);
        }

        $bill_amount_sum = array_sum($bill_amount);
        $sub_mch_id = (new wechatService())->communityList($community_id);   
        
        //生成订单
        $data['appid'] = 'wx352362f198d9c56b';//公众账号ID
        $data['mch_id'] = '1484539292';//商户号
        $data['sub_appid'] = 'wx29ca4f972fc13f5c';//小程序id
        $data['sub_mch_id'] = $sub_mch_id;
        //return $sub_mch_id;
        //$data['sub_mch_id']='1521888701';//子商户id
        //查询子商户ID
        $data['nonce_str'] = (new wechatService())->createNoncestr();//随机字符串
        $data['body'] = $room_address[0].'物业缴费';//商品描述
        $data['out_trade_no'] =time().rand(100000,999999);//商户订单号
        $data['total_fee'] =  $bill_amount_sum*100;//总金额
        $data['spbill_create_ip'] = $_SERVER["REMOTE_ADDR"];//终端IP
        $data['notify_url'] = 'https://www.jfzhiwen.com/admin/Wechat/wxnotice';//通知urlwww.sqzhsq.com
        $data['trade_type'] = 'JSAPI';

        //$wxkey = $propertyinfo['wx_key'];//key
        $wxkey = 'asdfaASDFASDFASFasfsadf6546A84SA';    
        $data['sign'] = (new wechatService())->MakeSign($data,$wxkey);//签名
        
        // return json(['info' => $data]);
        //输出xml字符
        $xml = (new wechatService())->ToXml($data);
        
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $payInfo = (new wechatService())->post_curl_data($url,$xml);
        
        $payInfo = json_decode(json_encode(simplexml_load_string($payInfo, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        //var_dump($payInfo);
        if($payInfo['return_code'] !== 'SUCCESS'){
            return json(['info' => $payInfo['return_msg']]);
        }else{
            unset($id[0]);
            //添加进数据库
            $order['out_trade_no'] = $data['out_trade_no'];
            //$order['out_trade_no'] = 222;
            $order['time'] = date('Y-m-d H:i:s',time());
            //$order['trade_no'] = 111;
             $order['trade_no'] = $payInfo['prepay_id'];
             $order['user_id'] = $data['sub_openid'];
            foreach($id as $billid){
                $order['id'] = $billid;
                $billedit = (new appletService())->billEdit($order);
                if(empty($billedit)){
                    return json(['info' => '账单存储失败']);
                }
            }
            $billpay["user_id"]=$data['sub_openid'];
            $billpay["order_money"]=$bill_amount_sum;
            $billpay["pay_money"]=$bill_amount_sum;
            $billpay["out_trade_no"]=$data['out_trade_no'];
            $billpay["billid"]=serialize($id);
            $billpay["out_room_id"]=$out_room_id["0"];
            $billpay["room_address"]=$room_address["0"];
            $billpay["community_name"]=$community_name;
            $billpay["community_id"]=$community_id;
            
            $res=Db::table("billpay")->insert($billpay);
            if($res){
                $jsApiParameters['appId'] = $payInfo['sub_appid'];//小程序appid
                $jsApiParameters['timeStamp'] = time();
                // $jsApiParameters['nonceStr'] = $payInfo['nonce_str'];
                $jsApiParameters['nonceStr'] = (new wechatService())->createNoncestr();
                $jsApiParameters['package'] = 'prepay_id='.$payInfo['prepay_id'];
                $jsApiParameters['signType'] = 'MD5';
                // $jsApiParameters['paySign'] = $payInfo['sign'];
                $jsApiParameters['paySign'] = (new wechatService())->MakeSigns($jsApiParameters,$wxkey);
                $jsApiParameters['trade_no']=$order['trade_no'];
                return json_encode($jsApiParameters);    
            }
            
        }
    }

    //微信回调信息
    public function wxnotice(){
        $address = 'C:\phpStudy\WWW\zaozao\public\pay\wxnotice\\'.date('YmdHis').rand(100000,999999).'.txt';//文本路径
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);//将数据读入文本
        //$address="C:\phpStudy\WWW\anrans\public\pay\wxnotice\\20190531092526139715.txt";
        //获取异步返回的xml数据
        $xmldata = file_get_contents($address);
        //将xml数据转化为数组
        $result = json_decode(json_encode(simplexml_load_string($xmldata, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        
        //验证回调信息
        if($result){
            //如果成功返回了
            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                $payinfo=Db::table("billpay")->where('out_trade_no',$result['out_trade_no'])->find();
                if(!empty($payinfo)){
                    if($payinfo["order_status"]=="0"){
                        $paydata["id"]=$payinfo["id"];
                        $paydata["order_status"]="1";
                        $paydata['pay_time'] = $result['time_end'];
                        $paydata["transaction_id"]= $result['transaction_id'];
                        Db::table("billpay")->update($paydata);
                    }

                    //更改账单状态
                    $billid=unserialize($payinfo["billid"]);
                    foreach ($billid as $key => $value) {
                        $billinfo=(new billService())->billIdinfo($value);
                        if($billinfo["status"]!="TRADE_SUCCESS"){
                            $billdata['status'] = 'TRADE_SUCCESS';       
                            $billdata['pay_type'] = '微信';
                            $billdata['gmt_payment'] =  $result['time_end'];
                            $billdata['id'] = $value;
                             //修改数据
                            $billedit = (new billService())->billEdit($billdata);
                            //如果订单同步支付宝，则删除支付宝订单
                            if($billinfo["tongbu"]=="1"){
                                (new appletService())->alibilldel($billinfo['id']);
                                Db::table("bill")->where('id',$billinfo['id'])->update(["tongbu"=>"3"]);
                            }
                        } 
                        $detailed[]='费用类型: '.$billinfo['cost_type'];
                        $detailed[]= '账期: '.$billinfo['acct_period'];
                        $detailed[]='金额: '.$billinfo['bill_entry_amount'].'元';
                    }

                    if($payinfo["printing"]=="0"){
                        $community = (new billService())->communityMachine($payinfo['community_id']);
                        $machineCode = $community['machine_code'];//终端号
                        $community_name = $community['community_name'];//小区名称
                        $room_address = $payinfo['room_address'];//门牌号
                        $owner_name = (new billService())->billOwnerName($payinfo['out_room_id']);//业主姓名
                        $detailed = $detailed;//费用类型
                        $trade_no =$payinfo['out_trade_no'];//支付宝订单号
                        $pay_type = "微信";//付款类型
                        $bill_amount =$payinfo['pay_money'];//支付金额
                        $gmt_payment = $result['time_end'];//付款时间
                        $property = (new billService())->propertyIdName($community['property_id']);//收款单位
                        $printing = (new printDemo())->payprinting($machineCode,$community_name,$room_address,$owner_name,$detailed,$trade_no,$pay_type,$bill_amount,$gmt_payment,$property);
                       
                        if($printing){
                            Db::table('billpay')->where('id', $payinfo["id"])->update(['printing' => '1']);
                            foreach($billid as $id){
                                $dayin = Db::name('bill')->where('id', $id)->update(['printing' => '1']);
                            }
                            
                        }
                    }
                }
                  
               
                   
                   
                   
                   
                
                
            }
        }
    }


    
}